//
//  XJMeViewController.m
//  XinJiangMall
//
//  Created by Tzyang on 2018/4/2.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJMeViewController.h"

#import "XJMeTableViewCell.h"
#import "XJMeOrderCell.h"

#import "XJPersonSetViewController.h"
#import "XJMoreViewController.h"

#import <objc/message.h>
#import "XJLoginViewController.h" // 5-4
#import "XJShouCangViewController.h" // 5-14 我的收藏
#import "XJMyWalletViewController.h" // 5-23 我的钱包
#import "XJMyOrderViewController.h" // 5-26 我的订单
#import "XJOrderWaitPayViewController.h"
#import "XJOrderWaitReceiveViewController.h"
#import "XJOrderWaitEvaluateViewController.h"
#import "XJOrderFinishViewController.h"
#import "XJAfterSaleHistoryViewController.h" //6-20售后
#import "XJServiceIdentifierViewController.h" //7-7 服务认证



//model
#import "XJMeBadageModel.h" // 6-14

@interface XJMeViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, copy) NSArray * xjme_cellArray;

/**标记角标model 网络请求成功之后赋值。*/
@property(nonatomic, strong) XJMeBadageModel *badageModel;

@end

@implementation XJMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // self.navButtonLeft.hidden = YES;
    
    self.navTitle = @"个人中心";
    self.navButtonRight.hidden = NO;

    //隐藏黑线
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent  = NO;
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
//
    [self initSubView];
}
- (void)viewWillAppear:(BOOL)animated {
    BOOL isLogin = YES;
    if (!isLogin) {
        // 登录注册
        XJLoginViewController *loginVC = [[XJLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }else {
        
        NSString *name = [[NSUserDefaults standardUserDefaults] valueForKey:@"nickname"];
        NSString *avatar = [[NSUserDefaults standardUserDefaults] valueForKey:@"avatar"];
        NSString * phone = [[NSUserDefaults standardUserDefaults] valueForKey:@"phone"];
        NSString * uuid = [[NSUserDefaults standardUserDefaults] valueForKey:@"uuid"];
        NSString *sex = [[NSUserDefaults standardUserDefaults] valueForKey:@"sex"];
        
        [self.xjme_headerV configureXJMeHeaderViewWithName:name sex:sex phone:phone userNumber:uuid iconStr:avatar];
        
        [self requestWaitPayOrderCount];
    }
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    //[self.navigationController setNavigationBarHidden:NO animated:YES];
//    self.tabBarController.tabBar.hidden=NO;
//}

- (UITableView *)xjme_tableView{
    
    if (!_xjme_tableView) {
        UITableView * xjme_tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
        xjme_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.xjme_tableView = xjme_tableView;
        [self.view addSubview:xjme_tableView];
    }
    return _xjme_tableView;
}

- (XJMeHeaderView *)xjme_headerV{
    
    if (!_xjme_headerV) {
        XJMeHeaderView * xjme_headerV = [[XJMeHeaderView alloc]initWithFrame:CGRectMake(0, 0, KWidth, ADAPTWidth(115))];
        self.xjme_headerV = xjme_headerV;
        [self.view addSubview:xjme_headerV];
//        xjme_headerV.backgroundColor = [UIColor redColor];
        
        XJWeakSelf(self);
        _xjme_headerV.clickHeadeIconBlock = ^{
            XJLog(@"点击了头像icon");
            [weakself my_personal];
        };
    }
    return _xjme_headerV;
}

- (void)initSubView{
    
    self.xjme_tableView.backgroundColor                  = WHITE_COLOR;
    self.xjme_tableView.showsVerticalScrollIndicator     = NO;
    self.xjme_tableView.showsHorizontalScrollIndicator   = NO;

    self.xjme_tableView.delegate        =   self;
    self.xjme_tableView.dataSource      =   self;
    self.xjme_tableView.tableHeaderView =   self.xjme_headerV;
    [self setExtraCellLineHidden:self.xjme_tableView];
    
}

- (NSArray *)xjme_cellArray{
    if (!_xjme_cellArray) {
        _xjme_cellArray = @[
                            @[@"个人设置",@"my_personal"],
                            @[@"我的钱包",@"my_wallet"],
                            @[@"服务认证",@"my_serviceIdentity"],
                            @[@"我的收藏",@"my_collection"],
                            @[@"更多",@"my_set"]
                            ];        
    }
    return _xjme_cellArray;
    
}

#pragma mark tableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    } else{
        return self.xjme_cellArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        XJMeOrderCell * xjmo_cell = [XJMeOrderCell cellWithTableView:tableView];
        xjmo_cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        xjmo_cell.accessoryType   = UITableViewCellAccessoryNone;
        
        XJWeakSelf(self)
        // 事件回调
        xjmo_cell.allOrderBtnBlock = ^{
            [weakself clickAllOrderAction];
        };
        
        xjmo_cell.btnTypeBlock = ^(XJMeOrderCellBtnType buttonType) {
//            XJLog(@"buttonType :%ld",(long)buttonType);
            [weakself clickWaitPayWaitReceiveWaitEvaluateAndSoOn:buttonType];
        };
        
        // 显示角标
        xjmo_cell.xjme_badageModel = self.badageModel;
        
        return xjmo_cell;

    }else{
        XJMeTableViewCell * xjm_cell = [XJMeTableViewCell cellWithTableView:tableView];

        xjm_cell.selectionStyle      = UITableViewCellSelectionStyleGray;
        
        NSArray *rows                = self.xjme_cellArray[indexPath.row];
        xjm_cell.xjme_cellImgV.image = [UIImage imageNamed:[rows lastObject]];
        xjm_cell.xjme_cellLab.text   = [rows firstObject];
       
        //显示钱包余额
        if (indexPath.row == 1) xjm_cell.yuELb.hidden = NO;
        
        return xjm_cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return ADAPTHeight(141);
    }
    return ADAPTHeight(44);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section!=0) {
        NSArray *array   = self.xjme_cellArray[indexPath.row];
        
        NSString *item   = [array lastObject];
        
        SEL cellSelector = NSSelectorFromString(item);
        
        if ([self respondsToSelector:cellSelector]) {
            ((void (*)(id, SEL))objc_msgSend)(self,cellSelector);
        }
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.3;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 0, KWidth-20, 0.3)];
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, KWidth-20, 0.3)];
    [view addSubview:backView];
    backView.backgroundColor = XJCOLOR_RGB(206, 211, 213);
    return view;
}

//设置分割线
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
        if (indexPath.row < self.xjme_cellArray.count) {
            //四个参数：上左下右
            cell.separatorInset=UIEdgeInsetsMake(0, 10, 0, 10);
        }
    }
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
//隐藏多余分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
}


#pragma mark cell 点击

- (void)my_personal{
    
    XJPersonSetViewController * xjPerVC = [[XJPersonSetViewController alloc]init];
    [self.navigationController pushViewController:xjPerVC animated:YES];
}


- (void)my_wallet{
    
    XJLog(@"点击我的钱包");
    
    XJMyWalletViewController *walletVC = [[XJMyWalletViewController alloc] init];
    [self.navigationController pushViewController:walletVC animated:YES];
}

- (void)my_serviceIdentity {
    XJLog(@"点击服务认证");
    
    XJServiceIdentifierViewController *serviceIdVC = [XJServiceIdentifierViewController new];
    
    [self.navigationController pushViewController:serviceIdVC animated:YES];
}

- (void)my_collection{
    
    XJLog(@"点击我的收藏");
    XJShouCangViewController *scVC = [[XJShouCangViewController alloc] init];
    [self.navigationController pushViewController:scVC animated:YES];
}

- (void)my_set{
    
    XJMoreViewController * xjMoreVC = [[XJMoreViewController alloc]init];
    [self.navigationController pushViewController:xjMoreVC animated:YES];
}

#pragma mark - 我订单cell 回调事件
- (void)clickAllOrderAction {
    XJLog(@"全部订单");
    
    XJMyOrderViewController *orderVC = [[XJMyOrderViewController alloc] init];
    [self.navigationController pushViewController:orderVC animated:YES];
}

- (void)clickWaitPayWaitReceiveWaitEvaluateAndSoOn:(XJMeOrderCellBtnType)type{
    
    
    switch (type) {
        case XJMeOrderCellBtnTypeWaitPay:
        {
            XJLog(@"待付款");
            XJMyOrderViewController *myOrderVC = [XJMyOrderViewController new];
            myOrderVC.currentIndex = 1; //1待付款。
            [self.navigationController pushViewController:myOrderVC animated:YES];

        } break;
            
        case XJMeOrderCellBtnTypeWaitReceive:
        {
            XJLog(@"待收货");
            XJMyOrderViewController *myOrderVC = [XJMyOrderViewController new];
            myOrderVC.currentIndex = 2; //2待收货。
            [self.navigationController pushViewController:myOrderVC animated:YES];
        }break;
            
        case XJMeOrderCellBtnTypeWaitEvaluate:
        {
            XJLog(@"待评价");
            XJMyOrderViewController *myOrderVC = [XJMyOrderViewController new];
            myOrderVC.currentIndex = 3; //3评价。
            [self.navigationController pushViewController:myOrderVC animated:YES];
        } break;
            
        case XJMeOrderCellBtnTypeFinish:
        {
            XJMyOrderViewController *myOrderVC = [XJMyOrderViewController new];
            myOrderVC.currentIndex = 4; //4已完成。
            [self.navigationController pushViewController:myOrderVC animated:YES];
            XJLog(@"已经完成");
        }break;
            
        case XJMeOrderCellBtnTypeAfterSale:{
         
            XJAfterSaleHistoryViewController *afterVc = [XJAfterSaleHistoryViewController new];
            [self.navigationController pushViewController:afterVc animated:YES];
            XJLog(@"售后");
        }
            break;
        default:
            break;
    }
}

#pragma mark - 这里回调用两个接口
- (void)requestWaitPayOrderCount{
    [XJHttpTool requestOrderOrderCountSuccessH:^(id responseObjc) {

        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            // 字典 转 角标模型model
            NSDictionary *contentDic = responseObjc[@"data"][@"content"];
            self.badageModel = [XJMeBadageModel mj_objectWithKeyValues:contentDic];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.xjme_tableView reloadData];
            });
            
        }else {
            [JRToast showWithText:responseObjc];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}


/**
http://xinjiangapi.zertone1.com/api/v1/order/orderCount

{
    "code": 0,
    "data": {
        "content": {
            "wait_receive_count": 0,
            "wait_pay_count": 50,
            "completed_count": 0,
            "refund_count": 0,
            "wait_comment_count": 0
        }
    }
}


http://xinjiangapi.zertone1.com/api/v1/customer/detail
*/


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
